<template>
  <!-- 电池簇 配置 -->
  <a-form
    :model="form"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    layout="vertical"
    ref="formRef"
    :rules="rules"
    :disabled="!configData.isEdit"
  >
    <a-form-item label="所属厂商" name="supplierId">
      <a-select
        v-model:value="form.supplierId"
        class="formInput"
        placeholder="请选择"
        @change="changeSupplierType"
        allow-clear
        :loading="formLoading"
      >
        <a-select-option
          v-for="item in supplierList"
          :value="item.supplierId"
          :key="item.supplierId"
        >
          {{ item.supplierShortName }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="所属型号" name="typeId">
      <a-select
        v-model:value="form.typeId"
        class="formInput"
        placeholder="请选择"
        :disabled="!form.supplierId || !configData.isEdit"
        allow-clear
        :loading="formLoading"
        @change="changeType"
      >
        <a-select-option
          v-for="item in supplierTypeList"
          :value="item.id"
          :key="item.id"
        >
          {{ item.type }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="电池簇名称" name="name">
      <a-input v-model:value="form.name" class="formInput" />
    </a-form-item>
    <a-form-item label="电池簇唯一标识">
      <a-input v-model:value="form.idx" class="formInput" />
    </a-form-item>
    <a-form-item label="资产设备编号" name="orderNum">
      <a-input v-model:value="form.orderNum" class="formInput" />
    </a-form-item>
    <a-form-item label="电池簇资产编码" name="assetCode">
      <a-input v-model:value="form.assetCode" class="formInput" />
    </a-form-item>
    <a-form-item label="PACK数量/电池簇">
      <a-input v-model:value="form.packNum" class="formInput" />
    </a-form-item>
    <a-form-item label="电芯数量/PACK">
      <a-input v-model:value="form.cellNum" class="formInput" />
    </a-form-item>
    <a-form-item>
      <div class="configBtn" @click="handleBattery">电芯配置</div>
    </a-form-item>
  </a-form>
  <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
    <a-button v-if="!configData?.isEdit" type="primary" @click="handleEdit"
      >编辑</a-button
    >
    <a-button
      v-else
      type="primary"
      @click.prevent="onSubmit"
      :loading="stionConfigState.configDataSaveLoading"
      >保存</a-button
    >
  </a-form-item>

  <a-modal
    v-model:open="batteryVisible"
    :title="`电芯配置-${form.name}`"
    class="addStation"
    destroyOnClose
    :width="620"
    @cancel="cancelBattery"
    centered
  >
    <a-table
      :columns="columns"
      :data-source="tableData"
      bordered
      :pagination="false"
      :scroll="{ x: 'max-content' }"
      @resizeColumn="handleResizeColumn"
      class="batteryTable"
    >
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'name'">
          <div>
            <a-input
              v-model:value="record.name"
              class="batteryInput"
              placeholder="请输入电芯名称"
              allow-clear
            />
          </div>
        </template>
        <template v-if="column.dataIndex === 'idx'">
          <div>
            <a-input
              v-model:value="record.idx"
              class="batteryInput"
              placeholder="请输入唯一标识"
              allow-clear
            />
          </div>
        </template>
        <!-- <template v-if="column.dataIndex === 'handle'">
          <div class="editable-row-operations">
            <span>
              <a-button type="link" danger @click="delData(index)"
                >删除</a-button
              >
            </span>
          </div>
        </template> -->
      </template>
    </a-table>
    <div class="addBtn">
      <div class="btn" @click="handleAdd"><PlusOutlined />新增</div>
    </div>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancelBattery">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="batteryVisible = false"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import { EQUIP_TYPE } from "@/constants/stationConfig";
import { useStionConfigStore } from "@/stores/stationConfig";
import { cloneDeep } from "lodash-es";
const { stionConfigState, changeConfigData } = useStionConfigStore();
const configData = computed(() => stionConfigState.configData);
const props = defineProps({
  draggableEl: {
    type: Array,
  },
});
watch(
  () => configData,
  async (val) => {
    handleInit();
  },
  { deep: true }
);
const $api = inject("$api");
const emits = defineEmits(["getConfig"]);
const form = ref({
  name: null,
  idx: null,
  assetCode: null,
  orderNum: null,
  packNum: null,
  cellNum: null,
  supplierId: null,
  typeId: null,
  type: EQUIP_TYPE.DIAN_CHI_CU,
  batteryModelId: null, // 电芯模版id，后端要求传。获取方式是从左侧器部件列表中获取电芯模版id
});
const formRef = ref(null);
const rules = {
  supplierId: [{ required: true, message: "请选择", trigger: "change" }],
  typeId: [{ required: true, message: "请选择", trigger: "change" }],
  name: [{ required: true, message: "请输入", trigger: "change" }],
  assetCode: [{ required: true, message: "请输入", trigger: "change" }],
  orderNum: [{ required: true, message: "请输入", trigger: "change" }],
  isBreaker: [{ required: true, message: "请选择", trigger: "change" }],
  breakerName: [{ required: true, message: "请输入", trigger: "change" }],
  breakerAssetCode: [{ required: true, message: "请输入", trigger: "change" }],
};
const columns = ref([
  {
    title: "电芯名称",
    dataIndex: "name",
    key: "name",
    resizable: true,
    align: "center",
  },
  {
    title: "唯一标识",
    dataIndex: "idx",
    key: "idx",
    resizable: true,
    align: "center",
  },
]);
const supplierList = ref([]);
const supplierTypeList = ref([]);
const batteryVisible = ref(false);
const tableData = ref([
  {
    name: "",
    idx: "",
  },
]);
const getSupplierTypeTree = async () => {
  const res = await $api.supplierTypeTree();
  supplierList.value = res.data;
};
const handleSupplierTypeList = (id) => {
  supplierTypeList.value =
    supplierList.value.filter((item) => item.supplierId === id)[0]
      ?.supplierTypeEntities || [];
};
const changeSupplierType = (id) => {
  form.value.typeId = null;
  handleSupplierTypeList(id);
};
const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      form.value.batteryModelId = props.draggableEl.find(
        (item) => item.modelType === EQUIP_TYPE.DIAN_XIN
      )?.id;
      form.value.batteryEntityList = tableData.value;
      form.value.type = EQUIP_TYPE.DIAN_CHI_CU;
      emits("getConfig", toRaw(form));
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const changeType = async () => {
  if (form.value.packNum || form.value.cellNum) {
    return;
  }
  // 没packNum和cellNum再进行默认值拉取处理
  const params = {
    supplierId: form.value.supplierId,
    typeId: form.value.typeId,
    businessType: 0,
    current: 1,
    size: 10,
  };
  const res = await $api.supplierTypePage(params);
  if (res.code === 0 && res?.data?.records.length) {
    form.value.packNum = res.data.records[0].packNumberPerCluster;
    form.value.cellNum = res.data.records[0].cellNumberPerPack;
  }
};
const handleEdit = () => {
  changeConfigData({
    ...stionConfigState.configData,
    isEdit: true,
  });
};
const handleInit = async () => {
  form.value = cloneDeep(stionConfigState.configData);
  const supplierId =
    stionConfigState.configData.supplierId ||
    stionConfigState.equipData.supplierId;
  const typeId =
    stionConfigState.configData.typeId ||
    stionConfigState.equipData.supplierTypeId;
  form.value.supplierId = supplierId;
  handleSupplierTypeList(supplierId);
  tableData.value = form.value?.batteryEntityList || [];
  if (!tableData.value?.length) {
    tableData.value.push({
      name: "",
      idx: "",
    });
  }
  await nextTick();
  form.value.typeId = typeId;
  if (supplierId && typeId) {
    changeType();
  }
};
const cancelBattery = () => {
  batteryVisible.value = false;
  tableData.value = [
    {
      name: "",
      idx: "",
    },
  ];
};
const delData = (index) => {
  tableData.value.splice(index, 1);
};
const handleAdd = () => {
  tableData.value.push({
    name: "",
    idx: "",
  });
};
const handleBattery = () => {
  if (configData.value.isEdit) {
    batteryVisible.value = true;
  }
};
onMounted(async () => {
  await getSupplierTypeTree();
});
const labelCol = { style: { width: "150px" } };
const wrapperCol = { span: 14 };
defineExpose({ handleInit });
</script>
<style lang="less" scoped>
.formInput {
  width: 175px;
  text-align: left;
}
.formSelect {
  width: 175px;
  text-align: left;
}
.configBtn {
  color: #1655ad;
  cursor: pointer;
  text-decoration: underline;
  width: 60px;
}
.addBtn {
  margin: 10px 10px 10px 0;
  text-align: right;
  .btn {
    cursor: pointer;
    width: 50px;
    display: inline-block;
    color: #1668dc;
  }
}
.batteryInput {
  width: 250px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.batteryTable {
  margin-top: 20px;
}
</style>